package com.lanou3g.ptp.api.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.lanou3g.ptp.api.resolver.annotation.SsoTeacher;
import com.lanou3g.ptp.entity.College;
import com.lanou3g.ptp.entity.Teacher;
import com.lanou3g.ptp.organize.service.CollegeService;
import com.lanou3g.ptp.teacher.service.TeacherService;
import com.lanou3g.ptp.utils.PtpResult;
import com.lanou3g.ptp.utils.PtpResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Api(description = "教师接口")
@RestController
public class TeacherController {

    @Reference
    private TeacherService teacherService;
    @Reference
    private CollegeService collegeService;

    @ApiOperation("查询某学校所有教师(包括所有基地教师)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "schoolId", value = "学校ID"),
            @ApiImplicitParam(name = "page", value = "页数"),
            @ApiImplicitParam(name = "size", value = "显示条数")
    })
    @GetMapping("/school/{schoolId}/teachers")
    public PtpResult list(@PathVariable Long schoolId,
                          @RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "size", defaultValue = "10") Integer size) {

        PageInfo<Teacher> all = teacherService.findBySchoolId(schoolId, page, size);
        return PtpResultUtils.ok(all);
    }

    @ApiOperation("根据id查询教师")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "教师Id")
    })
    @GetMapping("/teacher/{id}")
    public PtpResult findById(@PathVariable Long id) {

        Teacher teacher = teacherService.findById(id);
//        User user = userService.userById(teacher.getId());
//
//        HashMap<Object, Object> result = new HashMap<>();
//        result.put("id", teacher.getId());
//        result.put("name", user.getName());
//        result.put("gender", teacher.getGender());
//        result.put("phone", user.getTel());
//        result.put("type", teacher.getType());

        return PtpResultUtils.ok(teacher);
    }


    @ApiOperation("根据id删除教师")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "教师Id")
    })
    @DeleteMapping("/teacher/{id}")
    public PtpResult deleteById(@PathVariable Long id) {

        try {
            teacherService.deleteById(id);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }


    @ApiOperation("批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "多个教师id")
    })
    @DeleteMapping("/teachers/{ids}")
    public PtpResult deleteByIds(@PathVariable Long[] ids) {
        teacherService.deleteByIds(ids);
        return PtpResultUtils.ok();
    }


    @ApiOperation("查询教师列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数"),
            @ApiImplicitParam(name = "size", value = "显示条数"),
            @ApiImplicitParam(name = "keyword", value = "关键字")
    })
    @GetMapping("/teacher/name")
    public PtpResult searchByKeyword(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                     @RequestParam(value = "size", defaultValue = "10") Integer size,
                                     String keyword) {
        try {
            PageInfo<Teacher> teacherList;
            if (keyword != null && !keyword.trim().equals("")) {
                teacherList = teacherService.findByKeyword(page, size, keyword);
                System.out.println(teacherList);
            } else {
                teacherList = teacherService.findAll(page, size);
            }
            return PtpResultUtils.ok(teacherList);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }


    @ApiOperation("根据id更改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "教师ID")
    })
    @PutMapping("/teacher/{id}")
    public PtpResult update(@PathVariable Long id,
                            @RequestBody Teacher teacher) {

        try {
            teacher.setId(id);
            teacher.getUser().setId(id);
            teacherService.updateById(teacher);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }


    @ApiOperation("添加教师")
    @PostMapping("/teacher")
    public PtpResult insert(@RequestBody Teacher teacher) {
        try {
            teacherService.insert(teacher);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }


    @ApiOperation("导出Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "id数组")
    })
//    @GetMapping("/teacher/download/{ids}")
    public PtpResult getTeachers(@PathVariable Long[] ids) {

        try {
            List<Teacher> data = teacherService.getData(ids);
            return PtpResultUtils.ok(data);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }

    @ApiOperation("导入教师Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teacherUploadFile", value = ".xlsx文件")
    })
    @PostMapping("/teacher/import")
    public PtpResult importTeachers(@RequestBody byte[] bytes) {
        int count = teacherService.excelToTeacherInfo(bytes);
        return count > 0 ? PtpResultUtils.ok(count) : PtpResultUtils.error(500);
    }

    //    TODO 测试导入教师
    @ApiOperation("测试导入教师文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "testFile", value = "测试文件接收")
    })
    @PostMapping("/teacher/test")
    public PtpResult test(MultipartFile file) {
        InputStream inputStream;
        int count = 0;
        try {
            inputStream = file.getInputStream();
            byte[] bytes = IOUtils.toByteArray(inputStream);
            count = teacherService.excelToTeacherInfo(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return count > 0 ? PtpResultUtils.ok(count) : PtpResultUtils.error(500);
    }


    @ApiOperation("导出TeacherExcel模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户码", required = true, paramType = "header")
    })
    @GetMapping("/teacher/model")
    public PtpResult exportTeacherModel(@ApiIgnore @SsoTeacher Teacher teacher,
                                        HttpServletResponse response) {
        College college = collegeService.findById(teacher.getCollegeId());

        byte[] bytes = teacherService.getInfoModelExcelByCollegeId(college.getId());

        response.reset();
        response.setContentType("application/octet-stream;charset=utf-8");
        try {
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode(college.getName() + "教师信息表.xlsx", "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            IOUtils.write(bytes, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return PtpResultUtils.ok();
    }

    @ApiOperation("启用教师")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teacherId", value = "教师ID")
    })
    @PutMapping("/teacher/{teacherId}/enable")
    public PtpResult enableTeacher(@PathVariable Long teacherId) {
        boolean success = teacherService.enable(teacherId);
        return success ? PtpResultUtils.ok() : PtpResultUtils.error(500);
    }

    @ApiOperation("停用教师")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teacherId", value = "教师ID")
    })
    @PutMapping("/teacher/{teacherId}/disable")
    public PtpResult disableTeacher(@PathVariable Long teacherId) {
        boolean success = teacherService.disable(teacherId);
        return success ? PtpResultUtils.ok() : PtpResultUtils.error(500);
    }

}
